package gapidt.analysis;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IParent;
import org.eclipse.jdt.core.JavaModelException;

public class APIDesignAnalyzer {
	
	protected List<IDesignProblemsDetector<?>> detectors = new ArrayList<IDesignProblemsDetector<?>>();
	
	public List<IDesignProblemsDetector<?>> getDetectors() {
		return detectors;
	}

	public void setDetectors(List<IDesignProblemsDetector<?>> detectors) {
		this.detectors = detectors;
	}
	
	/**
	 * Adds a new design problems detector
	 * @param detector
	 */
	public void addDetector(IDesignProblemsDetector<?> detector){
		this.detectors.add(detector);
	}
	
	/**
	 * Removes the given design problems detector
	 * @param detector
	 */
	public void removeDetector(IDesignProblemsDetector<?> detector){
		this.detectors.remove(detector);
	}
	
	/**
	 * Analyze the design of the given Java element
	 * @param detector
	 */
	@SuppressWarnings("unchecked")
	public <T> APIDesignAnalysisResult<T> analyzeDesign(T node){
		APIDesignAnalysisResult<T> result = new APIDesignAnalysisResult<T>(node);
		
		for(IDesignProblemsDetector<?> detector : detectors)
			//Detector habilitado para este tipo de objetos
			if(detector.getSubjectClass().isAssignableFrom(node.getClass()))
				result.addAllDesignProblems(((IDesignProblemsDetector<T>) detector).detectProblems(node));
		
		try{
			if(node instanceof IParent && ((IParent) node).hasChildren())
				for(IJavaElement child : ((IParent) node).getChildren())
					result.addChildResult(analyzeDesign(child));

		}catch(JavaModelException e){
			e.printStackTrace();
		}

		return result;
	}
}
